/**
 * @see https://umijs.org/zh-CN/plugins/plugin-access
 * */

const flatTree = (tree: any) => {
  const res: any = [];
  if (!tree) {
    return res;
  }
  tree.forEach((item: any) => {
    if (item.permission) {
      item.permission.forEach((p: any) => {
        res.push(p);
      });
    }
  });
  return res;
};

// export default function access(initialState: { currentUser?: API.CurrentUser } | undefined) {
export default function access(initialState: { currentUser?: any } | undefined) {
  const { currentUser } = initialState ?? {};
  const usernameId = currentUser && currentUser.id;
  const power = currentUser ? flatTree(currentUser.character) : [];
  return {
    canSubPage: usernameId === '1' || power.some((item: any) => item.name === '权限管理页'),
    canAdmin: () => {
      return usernameId === '1' || power.some((item: any) => item.name === '权限管理页');
    },
    canSubFront: usernameId === '1' || power.some((item: any) => item.name === '前端部门'),
    canEnd: usernameId === '1' || power.some((item: any) => item.name === '后端部门'),
    can3Dpoint: usernameId === '1' || power.some((item: any) => item.name === '3D点云'),
    canSql: usernameId === '1' || power.some((item: any) => item.name === '数据部门'),
    canExchange: usernameId === '1' || power.some((item: any) => item.name === '交流模块'),
  };
}

export function isCheckPermission(
  initialState: { currentUser?: any } | undefined,
  permissionName: string,
  permissionType: string,
) {
  const { currentUser } = initialState ?? {};
  const power = currentUser ? flatTree(currentUser.character) : [];
  const usernameId = currentUser && currentUser.id;
  if (usernameId === '1') {
    return true;
  }
  const res = power.some(
    (item: any) => item.name === permissionName && item.type === permissionType,
  );
  return res;
}
